/*
 * Copyright (c) 2022 Kirky
 * Licensed under the Open Software Licence, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://opensource.org/licenses/osl-3.0.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lingeringdream.luciole.slice;

import com.lingeringdream.luciole.ResourceTable;
import com.lingeringdream.luciole.helper.PreferencesHelper;
import com.lingeringdream.luciole.helper.ResourceHelper;
import com.lingeringdream.luciole.helper.generalDialog.GeneralButtonElement;
import com.lingeringdream.luciole.helper.generalDialog.GeneralDialogHelper;
import com.lingeringdream.luciole.helper.hwid.HuaweiAccountHelper;
import com.lingeringdream.luciole.model.Constants;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Checkbox;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.window.service.WindowManager;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

/**
 * 初始化页面
 *
 * @author Kirky
 * @version 1.0
 * @date 2022/4/24
 */
public class InitializationSlice extends AbilitySlice {
    private final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP, 0x01, InitializationSlice.class.getName());
    private PreferencesHelper preferencesHelper;
    private Checkbox checkbox;
    private boolean LOGIN = false, AGREE = false;
    private HuaweiAccountHelper huaweiAccountHelper;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_silce_initialization);

        huaweiAccountHelper = new HuaweiAccountHelper();
    }

    @Override
    protected void onActive() {
        super.onActive();
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION);
        preferencesHelper = PreferencesHelper.getInstance(getContext());
        boolean use = preferencesHelper.getBoolean(Constants.USE.getValue());
        AGREE = preferencesHelper.getBoolean(Constants.AGREE.getValue());
        if (use) {
            HiLog.info(TAG, "直接进入主页面");
            goMainAbility();
        }
        LOGIN = preferencesHelper.getBoolean(Constants.LOGIN.getValue());
        initBottom();
        initAgreement();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (preferencesHelper != null) {
            preferencesHelper = null;
        }
    }

    /**
     * 初始化按钮
     */
    private void initBottom() {
        ShapeElement element = new ShapeElement(this, ResourceTable.Graphic_bg_button_emphasized);
        Component login = findComponentById(ResourceTable.Id_initialization_login);
        login.setBackground(element);
//        初始化
        Image image = login.findComponentById(ResourceTable.Id_iconButton_icon);
        image.setPixelMap(ResourceTable.Media_hw_logo_white);
        Text text = login.findComponentById(ResourceTable.Id_iconButton_content);
        text.setText(ResourceHelper.getString(this, ResourceTable.String_login_account,
                "登陆账号", null));
//        添加监听
        login.setClickedListener(component -> {
            if (judgeAgree(false)) {
                huaweiAccountHelper.signIn(getGlobalTaskDispatcher(TaskPriority.DEFAULT), getContext());
            }
        });

        element = new ShapeElement(this, ResourceTable.Graphic_bg_button_normal);
        Component use = findComponentById(ResourceTable.Id_initialization_use);
        use.setBackground(element);
//        初始化
        image = use.findComponentById(ResourceTable.Id_iconButton_icon);
        image.setPixelMap(ResourceTable.Media_icon_white);
        text = use.findComponentById(ResourceTable.Id_iconButton_content);
        text.setText(ResourceHelper.getString(this, ResourceTable.String_use_derectly,
                "直接使用", null));
//        添加监听
        use.setClickedListener(component -> {
            if (judgeAgree(true)) {
                goMainAbility();
            }
        });
    }

    /**
     * 初始化隐私政策确认
     */
    private void initAgreement() {
        AGREE = preferencesHelper.getBoolean("agree");
        checkbox = findComponentById(ResourceTable.Id_initialization_checkBox);
        checkbox.setChecked(AGREE);

        checkbox.setCheckedStateChangedListener((component, state) -> AGREE = state);

        Text agreement = findComponentById(ResourceTable.Id_initialization_privacyAgreement);
        agreement.setClickedListener(component -> showAgreement());
    }

    /**
     * 跳转主界面
     */
    private void goMainAbility() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.lingeringdream.luciole.MainAbility")
                .build();
        intent.setOperation(operation);
        startAbility(intent);
        terminateAbility();
    }

    /**
     * 判断用户是否同意隐私政策
     *
     * @param use 判断当前操作是否是直接使用APP
     * @return true 同意 false 不同意
     */
    private boolean judgeAgree(boolean use) {
        if (AGREE) {
            preferencesHelper.putSync(Constants.AGREE.getValue(), true);
            preferencesHelper.putSync(Constants.USE.getValue(), true);
            preferencesHelper.putSync(Constants.LOGIN.getValue(), LOGIN);
            return true;
        } else {
//            弹出同意隐私政策dialog
            GeneralDialogHelper.Builder builder = new GeneralDialogHelper.Builder(getContext());
            builder.setTitle(ResourceHelper.getString(this, ResourceTable.String_read_confirmation,
                            "请仔细阅读并同意以下条款", null))
                    .addClickableContent(ResourceHelper.getString(this,
                                    ResourceTable.String_agreement, "《用户隐私政策》", null),
                            dialog -> {
//                        跳转隐私政策
                                showAgreement();
                                dialog.remove();
                            })
                    .addButton(ResourceHelper.getString(this, ResourceTable.String_cancel,
                            "取消", null), GeneralButtonElement.TYPE_NORMAL, GeneralDialogHelper::remove)
                    .addButton(ResourceHelper.getString(this, ResourceTable.String_agree,
                            "同意", null), GeneralButtonElement.TYPE_ACCENT, dialog -> {
                        checkbox.toggle();
                        dialog.remove();
                        if (use) {
                            HiLog.info(TAG, "直接使用");
                            goMainAbility();
                        } else {
                            HiLog.info(TAG, "登录账号");
                            huaweiAccountHelper.signIn(getGlobalTaskDispatcher(TaskPriority.DEFAULT), getContext());
                        }
                    })
                    .create()
                    .show();
        }
        return false;
    }

    /**
     * 跳转隐私政策
     */
    private void showAgreement() {
        HiLog.info(TAG, "跳转隐私政策");
        Intent intent = new Intent();
        intent.setParam("fileName", "RuleOfLuciole.html");
        present(new LocalResourceWebViewSlice(), intent);
    }

}
